package com.dish.action;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dish.bean.Dish;
import com.dish.utils.JDBCUtils;


/**
 * Servlet implementation class ShowDish
 */
@WebServlet("/ShowDish")
public class ShowDish extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowDish() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ArrayList<Dish> lst;
		try {
			lst = getData();
			request.setAttribute("lst", lst);
			request.getRequestDispatcher("dishlist.jsp").forward(request, response);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}
	private ArrayList<Dish> getData() throws SQLException
	{
		ArrayList<Dish> lst = new ArrayList<Dish>();
		Connection conn = null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		try {
			conn = JDBCUtils.getConnection();
			ps = conn.prepareStatement("select * from dish");
			rs = ps.executeQuery();
			while(rs != null && rs.next()) {
				Dish dih = new Dish();
				dih.setDishid(rs.getInt("dishid"));
				dih.setDishname(rs.getString("name"));
				dih.setDishdesc(rs.getString("description"));
				dih.setImg(rs.getString("img"));
				dih.setPrice(rs.getDouble("price"));
				lst.add(dih);
			}
			return lst;
		}catch(RuntimeException e) {
			e.printStackTrace();
			return null;
		}finally {
			JDBCUtils.free(rs, ps, conn);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
